﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.Management;
using System.Web.SessionState;

namespace Common
{
    public class User
    {
        private string email;

        public string DisplayName
        {
            get { return (string)HttpContext.Current.Session["DisplayName"]; }
        }
        public string FullName
        {
            get { return (string)HttpContext.Current.Session["FullName"]; }
        }
        public string Email
        {
            get
            {
                if ((string)HttpContext.Current.Session["Email"] != null)
                {
                    email = (string)HttpContext.Current.Session["Email"];
                }
                else { email = "未设置Email"; }
                return email;

            }
        }
        public string Memberof//办公室
        {
            get { return (string)HttpContext.Current.Session["Memberof"]; }
        }
    }

    public sealed class DomainUserInfo
    {
        public string DisplayName;
        public string FullName;
        public string Email;
        public string Memberof;//办公室
    }

    public static class UserHelper
    {
        /// <summary>
        /// 活动目录中的搜索路径，也可根据实际情况来修改这个值。
        /// </summary>
        public static string DirectoryPath = "LDAP://" + GetDomainName();

        public static string Test;

        /// <summary>
        /// 获取与指定HttpContext相关的用户信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static DomainUserInfo GetCurrentUserInfo(HttpContext context)
        {
            string loginName = GetUserLoginName(context);
            if (string.IsNullOrEmpty(loginName))
                return null;

            return GetUserInfoByLoginName(loginName);
        }

        /// <summary>
        /// 根据指定的HttpContext对象，获取登录名。
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetUserLoginName(HttpContext context)
        {
            if (context == null)
                return null;

            if (context.Request.IsAuthenticated == false)
                return null;

            string userName = context.User.Identity.Name;
            // 此时userName的格式为：UserDomainName\LoginName
            // 我们只需要后面的LoginName就可以了。

            string[] array = userName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (array.Length == 2)
                return array[1];

            return null;
        }


        /// <summary>
        /// 根据登录名查询活动目录，获取用户信息。
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public static DomainUserInfo GetUserInfoByLoginName(string loginName)
        {
            if (string.IsNullOrEmpty(loginName))
                return null;

            // 下面的代码将根据登录名查询用户在AD中的信息。
            // 为了提高性能，可以在此处增加一个缓存容器(Dictionary or Hashtable)。
            try
            {

                DirectoryEntry entry = new DirectoryEntry(DirectoryPath);
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + loginName + ")";

                search.PropertiesToLoad.Add("displayname");
                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                // 如果还需要从AD中获取其它的用户信息，请参考ActiveDirectoryDEMO
                SearchResult result = search.FindOne();
                if (result != null)
                {
                    DomainUserInfo info = new DomainUserInfo();
                    info.DisplayName = result.Properties["displayname"][0].ToString();
                    info.FullName = result.Properties["cn"][0].ToString();
                    info.Email = result.Properties["mail"][0].ToString();
                    info.Memberof = result.Properties["physicalDeliveryOfficeName"][0].ToString();
                    return info;
                }

            }
            catch
            {
                // 如果需要记录异常，请在此处添加代码。

            }
            return null;
        }


        private static string GetDomainName()
        {
            // 注意：这段代码需要在Windows XP及较新版本的操作系统中才能正常运行。
            SelectQuery query = new SelectQuery("Win32_ComputerSystem");
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
            {
                foreach (ManagementObject mo in searcher.Get())
                {
                    if ((bool)mo["partofdomain"])
                        return mo["domain"].ToString();
                }
            }
            return null;
        }

    }


}